package com.eh.proxy.virtual.icon;

import javax.swing.*;
import java.awt.*;
import java.net.URL;

/**
 * Created by David on 2016/5/3.
 */
public class ImageProxy implements Icon {
    private URL imageUrl;
    private Icon currentIcon;

    private Icon imageNotLoaded;
    private Icon imageLoaded;

    private boolean changed = false;

    public ImageProxy(URL url) {
        this.imageUrl = url;
        imageNotLoaded = new ImageNotLoaded();
        this.setCurrentIcon(imageNotLoaded);
    }

    @Override
    public void paintIcon(final Component c, Graphics g, int x, int y) {
        if (imageLoaded == null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(2000L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    imageLoaded = new ImageIcon(imageUrl, "CD 封面");
                    c.repaint();
                }
            }).start();
        } else if (!changed) {
            this.setCurrentIcon(imageLoaded);
            changed = true;
        }
        currentIcon.paintIcon(c, g, x, y);
    }

    @Override
    public int getIconWidth() {
        return currentIcon.getIconWidth();
    }

    @Override
    public int getIconHeight() {
        return currentIcon.getIconHeight();
    }

    public final void setCurrentIcon(Icon currentIcon) {
        this.currentIcon = currentIcon;
    }
}
